﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Globalization;

namespace iCalSync
{
    
    class IcsFile
    {
        public List<string> icsLines;
        public IEnumerator<string> icsEnum;
        public Dictionary<string,IcsEvent> Events { get; set; }
        public DateTime Debut {get; set;}
        public DateTime Fin { get; set; }

        public void Parse(string fileName)
        {
            ReadFile(fileName);
            icsEnum = icsLines.GetEnumerator();
            var Ci = new CultureInfo("fr-FR", false);
            Debut = DateTime.ParseExact("31/12/2099", "dd/MM/yyyy",Ci);
            Fin = DateTime.ParseExact("01/01/1920", "dd/MM/yyyy", Ci);
            while (icsEnum.MoveNext())
            {
                if (icsEnum.Current.ToUpper().Equals(IcsStrings.IcsEventStart))
                {
                    var icsEvent = CreateEvent();
                    icsEvent.ParseEvent(ref icsEnum);
                    Events.Add(icsEvent.ICalUID, icsEvent);
                    var Dte = (icsEvent.Start.DateTime == null) ? 
                        DateTime.ParseExact(icsEvent.Start.Date.Substring(0, 10), "yyyy-MM-dd", Ci) : 
                        DateTime.ParseExact(icsEvent.Start.DateTime.Substring(0, 10), "yyyy-MM-dd", Ci);
                    if (Dte < Debut) 
                        Debut = Dte;
                    if (Dte > Fin)
                        Fin = Dte;
                }
            }
        }

        private void ReadFile(string fileName)
        {
            StreamReader reader = null;
            try
            {
                reader = new StreamReader(fileName);
                String icsLine = string.Empty;
                string tempLine = string.Empty;
                while ((icsLine = reader.ReadLine()) != null)
                {
                    if ((icsLine.StartsWith(" ")) | (icsLine.StartsWith(char.ConvertFromUtf32(9))))
                    {
                        icsLines[icsLines.Count-1] = icsLines[icsLines.Count-1]+icsLine.Substring(1);
                    }
                    else
                    {
                        if (icsLines == null) icsLines = new List<string>();
                        icsLines.Add(icsLine);
                    }
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
            }
        }

        private IcsEvent CreateEvent()
        {
            if(Events == null) Events = new Dictionary<string,IcsEvent>();
            var ev = new IcsEvent();
            return ev;
        }
    }
}
